// 引用使用es6的module引入和定义
// 全局变量以g_开头
// 私有函数以_开头
import { Config } from 'config.js';

class Token {
  constructor() {
    this.tokenUrl = Config.restUrl + 'user/login';
  }

  verify(callback) {
    var token = wx.getStorageSync('token');
    if (!token) {
      this.getToken(callback);
    }
  }

  getToken(callback) {
    var that = this;
    wx.login({
      success: function (res) {
        wx.request({
          url: that.tokenUrl,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          data: {
            code: res.code
          },
          success: function (res) {
            var data = res.data.data;
            // console.log(data);
            wx.setStorageSync('token', data.session_key);
            wx.setStorage({
              key: 'is_login',
              data: data.is_login,
            })
            callback && callback(data);
          },
          fail: function (res) {
            // console.log(res);
          }
        })
      }
    })
  }
}

export { Token };